<?php
namespace Manage\Controller;

class LoginController extends CommonController {

    private $admin_user;
    private $admin_pass;
    const SESSION_NAME = 'ADMIN';

    protected function _initialize(){
        $this->admin_user = C('ADMIN_USER');
        $this->admin_pass = md5(C('ADMIN_PASSWORD'));
    }


    public function Index(){
        $this->Login();
    }

    public function Login(){
        if( IS_POST ){
            $user = trim(I('post.admin_name'));
            $pass = trim(I('post.admin_pass'));
            $verify = trim(I('post.verify'));

            if( $verify == '' ) $this->error('请输入验证码');
            if( $user == '' ) $this->error('请输入管理员账号');
            if( $pass == '' ) $this->error('请输入登录密码');

            //验证码
            $api = A('Api');
            if( ! $api->CheckVerifyCode($verify) ) $this->error('验证码错误');
            unset($api);
            //验证用户
            if( $user !== $this->admin_user ) $this->error('您输入的管理员账号错误');
            //验证密码
            if( md5($pass) !== $this->admin_pass ) $this->error('您输入的密码错误');

            //验证通过
            $this->save_session();
            //跳转
            $this->redirect('/Admin/Index');
        }else{
            $this->display('Login/Index');
        }
    }

    public function Logout(){
        session(self::SESSION_NAME, null);
        $this->redirect('Login');
    }

    private function save_session(){
        session(self::SESSION_NAME, 1);
    }
}